/**
 * Description: 下载工具类
 *
 * Created by hrx on 2023-04-11 11:23:04
 */

/**
 * 保存 Blob
 * @param  {Blob} blob
 * @param  {String} filename 想要保存的文件名称
 */
function saveBlob(blob: any, filename: any) {
  // @ts-ignore
  if (window?.navigator?.msSaveOrOpenBlob) {
    // @ts-ignore
    navigator?.msSaveBlob(blob, filename);
  } else {
    let href = window.URL.createObjectURL(blob);
    saveAs(href, filename)
  }
}

/**
 * 保存文件
 * @param href 链接目标的 URL
 * @param filename 想要保存的文件名称
 */
export function saveAs(href:string, filename: string) {
  let link = document.createElement('a');
  link.href = href;
  link.download = filename;
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(link.href);
}

/**
 * 获取向服务器请求目标文件地址blob对象
 * @param  {String} url 目标文件地址
 * @return {cb}
 */
export function getBlob(url: string, callback: (blob: any) => void) {
  if (!url) {
    throw new Error('url is empty')
  }
  let xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';
  xhr.onload = function() {
    if (xhr.status === 200) {
      callback && callback(xhr.response);
    }
  };
  xhr.send();
}

export function jsonp(url:string, callback: () => {}, callbackName:string) {
  // 这里的 "jsonCallBack" ，和调用的 jsonp 的 url 中的 callback 值相对应（见粗体字）
  // @ts-ignore
  window[callbackName] = callback
  let appendUrl = url + (url.indexOf('?') == -1 ? '?':'&') + `callback=${callbackName}&output=jsonp`;
  const JSONP = document.createElement('script');
  JSONP.type = 'text/javascript';
  JSONP.src = appendUrl
  document.head.appendChild(JSONP);
  setTimeout(() => {
    document.head.removeChild(JSONP)
  },500)
}

/**
 * 获取图片的base64
 * @param url 图片地址
 * @param fileType 图片文件格式
 * @param callback 回调函数
 */
export function getBase64(url: string, fileType: string, callback: (_baseUrl: string) => void) {
  // 通过构造函数来创建的 img 实例，在赋予 src 值后就会立刻下载图片
  let Img = new Image(),
    dataURL = '';
  Img.src = url;
  Img.setAttribute("crossOrigin", "*");
  Img.onload = function () { // 要先确保图片完整获取到，这是个异步事件
    let canvas = document.createElement("canvas"), // 创建canvas元素
      width = Img.width, // 确保canvas的尺寸和图片一样
      height = Img.height;
    canvas.width = width;
    canvas.height = height;
    // @ts-ignore
    canvas.getContext("2d").drawImage(Img, 0, 0, width, height); // 将图片绘制到canvas中
    dataURL = canvas.toDataURL('image/' + fileType); // 转换图片为dataURL
    callback && callback(dataURL);
  };
}

/**
 * 下载图片
 * @param url
 * @param filename
 * @param fileType
 */
export function downloadImage (url:string, filename:string, fileType:string) {
  let fn = filename || getFileName(url)
  downloadFile(url, fn)
}

/**
 * 下载图片, 先转成base64数据
 * @param url
 * @param filename
 * @param fileType
 */
export function downloadImageByDataUrl (url:string, filename:string, fileType:string) {
  getBase64(url, fileType, (_baseUrl:string) => {
    saveAs(_baseUrl, filename)
  });
}

/**
 * 下载文件
 * @param url
 * @param filename
 */
export const downloadFile = (url: string, filename: string) => {
  getBlob(url, (blob: any) => {
    let fn = filename || getFileName(url)
    saveBlob(blob, fn);
  });
}


/**
 * 根据文件url获取文件名
 * @param url 文件url
 */
export const getFileName = (url:string) => {
  let num = url.lastIndexOf('/')+1
  let fileName = url.substring(num)
  //把参数和文件名分割开
  fileName = decodeURI(fileName.split("?")[0]);
  return fileName;
}

export const download = (data: any, fileName: string, fileType: string) => {
  if (!data) {
    return
  }
  let date = new Date()
  let time = date.toLocaleDateString().replace(/\//g, '-')
  const _fileName = `${fileName}.${fileType}`
  const url = window.URL.createObjectURL(new Blob([data]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', 'excel.xlsx')
  link.download = _fileName
  document.body.appendChild(link)
  link.click()
}